package tcm.test.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tcm.test.pojo.dto.ProductDTO;
import tcm.test.pojo.entity.PageResult;
import tcm.test.pojo.entity.Product;
import tcm.test.pojo.entity.result;
import tcm.test.service.ProductService;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService ProductService;

    //添加新商品
    @PostMapping
    public result<String> register(@RequestBody ProductDTO productDTO) {
        log.info("添加新商品: {}", productDTO);
        ProductService.register(productDTO);
        return result.success();
    }

    //分页查询所有商品
    @GetMapping
    public result<PageResult> getAll(Integer page, Integer size) {
        log.info("获取全部商品数据");
        PageResult p = ProductService.getALL(page, size);
        return result.success(p);
    }

    //根据id查询商品
    @GetMapping("/{id}")
    public result<Product> getById(@PathVariable Long id) {
        log.info("根据id查询所有商品，{}", id);
        Product p = ProductService.getById(id);
        return result.success(p);
    }

    //根据id更新商品
    @PutMapping("/{id}")
    public result<String> update(@PathVariable Long id, @RequestBody ProductDTO productDTO)
    {
        log.info("根据id更新商品，{},{}", id, productDTO);
        productDTO.setId(id);
        ProductService.update(productDTO);
        return result.success();
    }

    //根据id删除商品
    @DeleteMapping("/{id}")
    public result<String> deleteById(@PathVariable Long id) {
        log.info("根据id删除商品,{}",id);
        ProductService.deleteById(id);
        return result.success();
    }
}